#!/bin/bash

source_dir='/home/openeuler/agiros/tars' # 将此目录改为实际存放ros-humble*.tar.gz的目录
dest_dir="/home/openeuler/agiros/processed_tar" # 此目录存放处理后的tar包
bak_dir="/home/openeuler/agiros/bak_tar"

cd $source_dir
# 创建临时工作目录
temp_dir=$(mktemp -d)
extracted_dir=$(mktemp -d)
mkdir -p "$dest_dir"
mkdir -p "$bak_dir"

# 遍历所有的 .tar.gz 文件
for tar_gz_file in ros-humble-*.tar.gz; do
    echo "Processing $tar_gz_file..."

    # 解压 .tar.gz 文件以提取 .tar 文件
    tar -xzf "$tar_gz_file" -C "$temp_dir"

    # 查找解压出的文件夹
    extracted_folder=$(find "$temp_dir" -mindepth 1 -maxdepth 1 -type d)

    if [ -n "$extracted_folder" ]; then
        # 处理提取的文件夹
        folder_name=$(basename "$extracted_folder")
        # 替换文件夹名称中的 "ros-humble-" 为 "agiros-loong-"
        new_folder_name=$(echo "$folder_name" | sed 's/^ros-humble-/agiros-loong-/')
        mv "$extracted_folder" "$extracted_dir/$new_folder_name"
        echo "Renamed $folder_name to $new_folder_name"

        # 创建新的 .tar.gz 文件
        new_tar_gz_file=$(echo "$tar_gz_file" | sed 's/^ros-humble-/agiros-loong-/')
        tar -czf "$new_tar_gz_file" -C "$extracted_dir" "$new_folder_name"
        echo "Created new tar.gz file: $new_tar_gz_file"
	mv "$new_tar_gz_file"  "$dest_dir/$new_tar_gz_file"
        echo "备份文件: $new_tar_gz_file"
	cp "$dest_dir/$new_tar_gz_file"  "$bak_dir/$new_tar_gz_file"  
        # 清理工作目录
        rm -rf "$extracted_dir/$new_folder_name"
    fi
done

# 清理临时工作目录
rm -rf "$temp_dir" "$extracted_dir"

echo "Processing completed!"